package com.autumn.oauth2.zero.provider.endpoint;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.provider.endpoint.FrameworkEndpoint;
import org.springframework.security.oauth2.provider.token.ConsumerTokenServices;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.autumn.util.StringUtils;

/**
 * 注销 Token 端点
 * 
 * @author 老码农
 *
 *         2018-04-12 18:51:31
 */
@FrameworkEndpoint
public class RevokeTokenEndpoint {

	private final ConsumerTokenServices consumerTokenServices;

	/**
	 * 
	 * @param consumerTokenServices
	 */
	public RevokeTokenEndpoint(ConsumerTokenServices consumerTokenServices) {
		this.consumerTokenServices = consumerTokenServices;
	}

	/**
	 * 注销
	 * 
	 * @param access_token
	 *            令牌
	 * @return
	 *
	 */
	@RequestMapping(method = RequestMethod.DELETE, value = "/oauth/token/{id}")
	public ResponseEntity<Boolean> revokeToken(String access_token) {
		if (StringUtils.isNullOrBlank(access_token)) {
			return getResponse(false);
		}
		return getResponse(consumerTokenServices.revokeToken(access_token));
	}

	private ResponseEntity<Boolean> getResponse(boolean success) {
		HttpHeaders headers = new HttpHeaders();
		headers.set("Cache-Control", "no-store");
		headers.set("Pragma", "no-cache");
		return new ResponseEntity<Boolean>(success, headers, HttpStatus.OK);
	}
}
